﻿using UnityEngine;
using System.Collections;

public class ballLauncher : MonoBehaviour {
	
	public Transform ballPrefab; 
	public float initialSpeed = 10.0f; 
	public Transform player1; 
	public Transform player2;
	public AudioClip timerSound; 
	public AudioClip launchSound;
	private Transform newball; 

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void LaunchBall (int player) { 
		//Transform newball; 
		//GameObject newball;
		if (player == 1) 
		{ 
			newball = (Transform)Instantiate(ballPrefab, player1.position + new Vector3(0,1,0), Quaternion.identity); 
			newball.parent = player1;
			audio.clip = timerSound; 
	 		audio.Play(); 
		 	//yield WaitForSeconds(1); 
			StartCoroutine(MyWait());
	 		audio.Play(); 
	 		//yield WaitForSeconds(1); 
			StartCoroutine(MyWait());
	 		audio.clip = launchSound; 
	 		audio.Play();  
			newball.parent = null; 
			newball.rigidbody.AddForce( new Vector3( 0, 1, 0) * initialSpeed ) ; 
		} 
		else 
		{ 
			newball = (Transform)Instantiate(ballPrefab, player2.position + new Vector3(0,-1,0), Quaternion.identity); 
			newball.parent = player2; 
			audio.clip = timerSound; 
	 		//audio.Play(); 
	 		//yield WaitForSeconds(1);
			StartCoroutine(MyWait());
	 		//audio.Play(); 
	 		//yield WaitForSeconds(1); 
			//StartCoroutine(MyWait());
	 		//audio.clip = launchSound; 
	 		//audio.Play(); 
			//newball.parent = null; 
			//newball.rigidbody.AddForce( new Vector3( 0, -1, 0) * initialSpeed ) ; 
		} 
	} 
	
	IEnumerator MyWait() {
		yield return new WaitForSeconds(1);	
		audio.Play();
		StartCoroutine(Wait ());
	}
	IEnumerator Wait() {
		yield return new WaitForSeconds(1);	
		audio.Play();
		StartCoroutine(WaitOneMore());
	}
	IEnumerator WaitOneMore(){
		yield return new WaitForSeconds(1);
		audio.clip = launchSound; 
 		audio.Play(); 
		newball.parent = null; 
		newball.rigidbody.AddForce( new Vector3( 0, -1, 0) * initialSpeed ) ; 
	}
}
